import axios from 'axios'
import { getToken } from '@/utils/auth'

export const exportRequest = async(method, url, data) => {
  const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 15000 // request timeout
  })
  const token = getToken()
  const headers = {
    'Authentication': token
  }
  const options = {
    method,
    url,
    headers,
    responseType: 'blob'
  }

  if (method.toLowerCase() === 'post') {
    options.data = data
  }
  if (method.toLowerCase() === 'get') {
    options.params = data
  }
  try {
    const res = await service(options)
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(res?.data)
    const fileName = res.headers['content-disposition'].split('=')[1]
    link.download = decodeURI(fileName)
    link.click()
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    throw new Error(error.message || '文件下载失败')
  }
}
